package com.summer.framework.gate.server.filter;


import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.zuul.context.RequestContext;
import com.summer.framework.common.entity.response.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @auther: 杨杰
 * @date: 2018/11/14 16:01
 * @description:
 */

@Slf4j
@Component
public class MyErrorFilter extends SendErrorFilter {

    @Value("${error.path:/error}")
    private String errorPath;

    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }


    @Override
    public Object run() {
        log.info("MyErrorFilter run");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        Throwable throwable = ctx.getThrowable();
        int socketTimeoutExIndex = ExceptionUtils.indexOfThrowable(throwable, java.net.SocketTimeoutException.class);
        int connectionExIndex = ExceptionUtils.indexOfThrowable(throwable, org.apache.http.conn.ConnectTimeoutException.class);
        int clientExIndex = ExceptionUtils.indexOfThrowable(throwable, com.netflix.client.ClientException.class);
        int hystrixExIndex = ExceptionUtils.indexOfThrowable(throwable, HystrixRuntimeException.class);

        List<Throwable> list = ExceptionUtils.getThrowableList(throwable);
        if (list.contains(HystrixRuntimeException.class)) {
            log.info("xxx");
            log.info(list.get(hystrixExIndex).getCause().toString());
            log.info(list.get(hystrixExIndex).getMessage());
        }


        for (Throwable item : list) {
            System.out.println("Throwable:" + item.toString() + "====item.getMessage()：" + item.getMessage());

        }


        String message = "";
        if (hystrixExIndex != -1) {
            message = list.get(hystrixExIndex).getMessage();
            /*if (connectionExIndex != -1) {
                //被调用的微服务挂掉了
                message = message.replace(" failed and no fallback available.", "微服务已经掉线");
            } else {
                //微服务所调用的feign客户端挂掉
                message = message.replace(" failed and no fallback available.", "微服务中调用的feign连接超时");
            }*/
        } else {
            message = ExceptionUtils.getRootCause(throwable).getMessage();
        }
        log.info("message:" + message);
        responseOutWithJson(response, new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), message));
        return null;
    }


    protected void responseOutWithJson(HttpServletResponse response,
                                       Object responseObject) {
        //将实体对象转换为JSON Object转换
        Object responseJSONObject = JSONObject.toJSON(responseObject);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(responseJSONObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}

